package com.woyowodaows.utils;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Base64;
import android.view.View;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;


/**
 * @author haiwei
 *         Bitmap处理工具类
 *         2017/B/22
 */
public class BitmapUtils {

    private static BitmapUtils mBitmapUtils;

    public static BitmapUtils getInstance() {
        if (mBitmapUtils == null) {
            synchronized (BitmapUtils.class){
                if (mBitmapUtils == null){
                    mBitmapUtils = new BitmapUtils();
                }
            }
        }
        return mBitmapUtils;
    }

    /**
     * 将view转为bitmap
     *
     * @param v
     * @return
     */
    public static Bitmap getViewBitmap(View v) {
        v.clearFocus();
        v.setPressed(false);

        boolean willNotCache = v.willNotCacheDrawing();
        v.setWillNotCacheDrawing(false);
        int color = v.getDrawingCacheBackgroundColor();
        v.setDrawingCacheBackgroundColor(0);

        if (color != 0) {
            v.destroyDrawingCache();
        }
        v.buildDrawingCache();
        Bitmap cacheBitmap = v.getDrawingCache();
        if (cacheBitmap == null) {
            return null;
        }

        Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);

        // Restore the view
        v.destroyDrawingCache();
        v.setWillNotCacheDrawing(willNotCache);
        v.setDrawingCacheBackgroundColor(color);

        return bitmap;
    }

    /***
     * 旋转Bitmap
     *
     * @param b
     * @param rotateDegree
     * @return
     */
    public static Bitmap getRotateBitmap(Bitmap b, float rotateDegree) {
        Matrix matrix = new Matrix();
        matrix.postRotate(rotateDegree);
        Bitmap rotaBitmap = Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(), matrix, false);
        return rotaBitmap;
    }

    /**
     * 设置图片大小，如果是放大图片，filter决定是否平滑，如果是缩小图片，filter无影响
     *
     * @param src
     * @param dstWidth
     * @param dstHeight
     * @return
     */
    public static Bitmap createScaleBitmap(Bitmap src, int dstWidth, int dstHeight) {
        Bitmap dst = null;
        try {
            dst = Bitmap.createScaledBitmap(src, dstWidth, dstHeight, false);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dst;
    }



    /**
     * 将图片保存到系统相册
     *
     * @param context
     * @param bmp
     */
    public static String saveImageToGallery(Context context, Bitmap bmp) {
        // 首先保存图片
        File appDir = new File(Environment.getExternalStorageDirectory(), "liwan");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 其次把文件插入到系统图库
//        try {
////            MediaStore.Images.Media.insertImage(context.getContentResolver(),
////                    file.getAbsolutePath(), fileName, null);
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        }
        // 最后通知图库更新
        Uri uri = Uri.parse("file://" + file.getAbsolutePath());
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,uri));
        File mPathFile = null;
        try {
            mPathFile = new File(new URI(uri.toString()));
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        return mPathFile.getPath();

    }





    /**
     * 保存指定长宽的BitMap图片
     *
     * @param
     * @param
     * @param (ratio--覆盖率(0~100))
     * @param (compressFormat-保存为那种jpg还是png)
     * @return
     */
    public static String saveBitmapWH(File file, int ratio, int w, int h, Bitmap.CompressFormat compressFormat) {
        String imgPath = null;
        Bitmap newBitmap = null;
        try {
            imgPath = file.getAbsolutePath();
            newBitmap = convertToBitmap(file.getAbsolutePath(), w, h);
            FileOutputStream out = new FileOutputStream(file);
            newBitmap.compress(compressFormat, ratio, out);
            Bitmap.createScaledBitmap(newBitmap, w, h, true);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            imgPath = "";
        } catch (IOException e) {
            e.printStackTrace();
            imgPath = "";
        } finally {
            if (newBitmap != null && !newBitmap.isRecycled()) {
                newBitmap.recycle();
            }
        }
        return imgPath;
    }

    /**
     * 保存指定宽度图片
     *
     * @param
     * @param compressFormat
     * @return
     * @throws FileNotFoundException
     */
    public static String saveBitmapWH(Bitmap bitmap, String filePath, int ratio, int w, int h, Bitmap.CompressFormat compressFormat) {
        if (!TextUtils.isEmpty(filePath)) {
            try {
                File newFile = new File(filePath);
                FileOutputStream outputStream = new FileOutputStream(newFile);
                bitmap.compress(compressFormat, ratio, outputStream);
                Bitmap.createScaledBitmap(bitmap, w, h, true);
                outputStream.flush();
                outputStream.close();
            } catch (FileNotFoundException e1) {
                e1.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (bitmap != null || !bitmap.isRecycled()) {
                    bitmap.recycle();
                }
            }
            return filePath;
        }
        return null;
    }



    /**
     * 加载指定大小图片
     *
     * @param path
     * @param w
     * @param h
     * @return
     */
    public static Bitmap convertToBitmap(String path, int w, int h) {
        BitmapFactory.Options opts = new BitmapFactory.Options();
        // 设置为True只获取图片大小
        opts.inJustDecodeBounds = true;
        opts.inPreferredConfig = Config.ARGB_8888;
        // 返回为空
        BitmapFactory.decodeFile(path, opts);
        int width = opts.outWidth;
        int height = opts.outHeight;
        float scaleWidth = 0.f, scaleHeight = 0.f;
        if (width > w || height > h) {
            // 缩放
            scaleWidth = ((float) width) / w;
            scaleHeight = ((float) height) / h;
        }
        opts.inJustDecodeBounds = false;
        float scale = Math.max(scaleWidth, scaleHeight);
        opts.inSampleSize = (int) scale;
        // WeakReference<Bitmap> weak = new
        // WeakReference<Bitmap>(BitmapFactory.decodeFile(path, opts));
        return Bitmap.createScaledBitmap(BitmapFactory.decodeFile(path, opts), w, h, true);
    }

    /**
     * 加载文件中图片
     *
     * @param path
     * @return
     */
    public static Bitmap convertToBitmap(String path) {
        return BitmapFactory.decodeFile(path);
    }

    /**
     * @param x              图像的宽度
     * @param y              图像的高度
     * @param image          源图片
     * @param outerRadiusRat 圆角的大小
     * @return 圆角图片
     */
    public static Bitmap createFramedPhoto(int x, int y, Bitmap image, float outerRadiusRat) {
        // 根据源文件新建一个darwable对象
        Drawable imageDrawable = new BitmapDrawable(image);
        // 新建一个新的输出图片
        Bitmap output = Bitmap.createBitmap(x, y, Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
        // 新建一个矩形
        RectF outerRect = new RectF(0, 0, x, y);
        // 产生一个红色的圆角矩形
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setColor(Color.RED);
        canvas.drawRoundRect(outerRect, outerRadiusRat, outerRadiusRat, paint);
        // 将源图片绘制到这个圆角矩形上
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        imageDrawable.setBounds(0, 0, x, y);
        canvas.saveLayer(outerRect, paint, Canvas.ALL_SAVE_FLAG);
        imageDrawable.draw(canvas);
        canvas.restore();
        return output;
    }


    /**
     * 将file转成byte数组
     *
     * @param filePath
     * @return
     */
    public byte[] fileSwitchBytes(String filePath) {
        byte[] buffer = null;
        try {
            File file = new File(filePath);
            FileInputStream fileInputStream = new FileInputStream(file);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n;
            while ((n = fileInputStream.read(b)) != -1) {
                byteArrayOutputStream.write(b, 0, n);
            }
            fileInputStream.close();
            byteArrayOutputStream.close();
            buffer = byteArrayOutputStream.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }

    /**
     * @param bitmap
     * @return
     */
    public String imgToBase64(Bitmap bitmap) {
        if (bitmap == null) {
            return null;
        }
        ByteArrayOutputStream out = null;
        try {
            out = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
            out.flush();
            out.close();
            byte[] imgBytes = out.toByteArray();
            return Base64.encodeToString(imgBytes, Base64.DEFAULT);
        } catch (Exception e) {
            return null;
        } finally {
            try {
                out.flush();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 将base64转图片
     * @param string
     * @return
     */
    public static Bitmap stringtoBitmap(String string) {
        //将字符串转换成Bitmap类型
        Bitmap bitmap = null;
        try {
            byte[] bitmapArray;
            bitmapArray = Base64.decode(string, Base64.DEFAULT);
            bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }


    }
